import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
    QTextEdit, QPushButton, QLineEdit, QRadioButton, QButtonGroup, QMessageBox
)
from PyQt5.QtCore import pyqtSignal, Qt, QObject, QTimer
from openai import OpenAI

# 配置 DeepSeek API
API_KEY = "sk-565505bad9db4ea086eb6d45b8bdd1bc"
BASE_URL = "https://api.deepseek.com"
client = OpenAI(api_key=API_KEY, base_url=BASE_URL)

class StreamSignal(QObject):
    update_text = pyqtSignal(str)
    update_speaker = pyqtSignal(str)

class DebateApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("鲁迅大战周树人 AI 辩论模拟器")
        self.resize(800, 600)

        self.messages_luxun = []
        self.messages_zhoushuren = []
        self.round = 0

        self.signal = StreamSignal()
        self.signal.update_text.connect(self.append_debate_text)
        self.signal.update_speaker.connect(self.append_speaker_text)

        self.setup_ui()

    def setup_ui(self):
        layout = QVBoxLayout()

        self.topic_input = QLineEdit()
        self.luxun_input = QLineEdit()
        self.zhoushuren_input = QLineEdit()

        layout.addWidget(QLabel("辩论话题："))
        layout.addWidget(self.topic_input)
        layout.addWidget(QLabel("鲁迅立场："))
        layout.addWidget(self.luxun_input)
        layout.addWidget(QLabel("周树人立场："))
        layout.addWidget(self.zhoushuren_input)

        layout.addWidget(QLabel("请选择先手："))
        self.luxun_first = QRadioButton("鲁迅先手")
        self.zhoushuren_first = QRadioButton("周树人先手")
        self.first_group = QButtonGroup()
        self.first_group.addButton(self.luxun_first)
        self.first_group.addButton(self.zhoushuren_first)
        hbox = QHBoxLayout()
        hbox.addWidget(self.luxun_first)
        hbox.addWidget(self.zhoushuren_first)
        layout.addLayout(hbox)

        self.start_button = QPushButton("开始辩论")
        self.start_button.clicked.connect(self.start_debate)
        layout.addWidget(self.start_button)

        self.debate_view = QTextEdit()
        self.debate_view.setReadOnly(False)
        layout.addWidget(QLabel("辩论内容："))
        layout.addWidget(self.debate_view)

        self.luxun_view = QTextEdit()
        self.luxun_view.setReadOnly(False)  # 改为可编辑
        self.zhoushuren_view = QTextEdit()
        self.zhoushuren_view.setReadOnly(False)  # 改为可编辑

        layout.addWidget(QLabel("鲁迅发言："))
        layout.addWidget(self.luxun_view)
        layout.addWidget(QLabel("周树人发言："))
        layout.addWidget(self.zhoushuren_view)

        self.next_button = QPushButton("下一轮")
        self.next_button.clicked.connect(self.next_round)
        layout.addWidget(self.next_button)

        self.setLayout(layout)

    def append_debate_text(self, text):
        cursor = self.debate_view.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        self.debate_view.setTextCursor(cursor)
        QApplication.processEvents()

    def append_speaker_text(self, text):
        if text.startswith("鲁迅"):
            self.luxun_view.append(f"第 {self.round} 轮：\n{text[3:]}\n")
        else:
            self.zhoushuren_view.append(f"第 {self.round} 轮：\n{text[4:]}\n")

    def start_debate(self):
        topic = self.topic_input.text()
        luxun_pos = self.luxun_input.text()
        zhoushuren_pos = self.zhoushuren_input.text()

        if not topic or not luxun_pos or not zhoushuren_pos:
            QMessageBox.warning(self, "提示", "请填写完整的话题和立场！")
            return

        self.messages_luxun = [
            {"role": "system",
             "content": f"假设你是选手A,对方是选手B，你在参加一场辩论赛，你支持：{luxun_pos}，应当坚持这个立场辩论，直到你无力反驳为止(也不要太倔强，觉得辩论不过就投降吧）。"}
        ]
        self.messages_zhoushuren = [
            {"role": "system",
             "content": f"假设你是选手B,对方是选手A,你在参加一场辩论赛，你支持：{zhoushuren_pos}，必须坚持这个立场辩论，直到你无力反驳为止(也不要太倔强，觉得辩论不过就投降吧）。"}
        ]

        self.round = 1
        self.debate_view.append(f"\n=== 第 {self.round} 轮辩论开始 ===")

        # 清空发言框
        self.luxun_view.clear()
        self.zhoushuren_view.clear()

        # 使用 QTimer 来处理下一轮的开始
        QTimer.singleShot(100, self.run_round)  # 延迟 100ms 后执行

    def next_round(self):
        self.round += 1
        self.debate_view.append(f"\n=== 第 {self.round} 轮辩论 ===")

        # 清空发言框
        self.luxun_view.clear()
        self.zhoushuren_view.clear()

        # 使用 QTimer 来处理下一轮的开始
        QTimer.singleShot(100, self.run_round)  # 延迟 100ms 后执行

    def run_round(self):
        # 根据先手顺序决定谁先发言
        if self.luxun_first.isChecked() or self.round == 1:
            self.run_turn("鲁迅", self.messages_luxun, self.messages_zhoushuren)
            self.run_turn("周树人", self.messages_zhoushuren, self.messages_luxun)
        else:
            self.run_turn("周树人", self.messages_zhoushuren, self.messages_luxun)
            self.run_turn("鲁迅", self.messages_luxun, self.messages_zhoushuren)

    def run_turn(self, name, speaker_history, listener_history):
        prompt = f"请继续辩论话题：{self.topic_input.text()}"
        speaker_history.append({"role": "user", "content": prompt})

        try:
            response = client.chat.completions.create(
                model="deepseek-chat",
                messages=speaker_history,
                stream=True
            )

            # 实时输出前缀
            self.signal.update_text.emit(f"[{name}]：")
            QApplication.processEvents()

            full_reply = ""
            for chunk in response:
                delta = chunk.choices[0].delta
                if delta and delta.content:
                    part = delta.content
                    full_reply += part
                    self.signal.update_text.emit(part)  # 每部分字符都 emit
                    QApplication.processEvents()  # 强制 UI 更新
            self.signal.update_text.emit("\n")
            self.signal.update_speaker.emit(f"{name}：{full_reply}")

            speaker_history.append({"role": "assistant", "content": full_reply})
            listener_history.append({"role": "user", "content": full_reply})

            # 在发言结束后让用户修改辩词
            self.enable_edit(name, full_reply)

        except Exception as e:
            QMessageBox.critical(self, "错误", f"获取 {name} 回复失败：{str(e)}")

    def enable_edit(self, speaker_name, speech):
        # 允许修改发言内容
        if speaker_name == "鲁迅":
            self.luxun_view.setText(speech)  # 显示辩词
        else:
            self.zhoushuren_view.setText(speech)  # 显示辩词

        # 在此可以修改辩词，用户可以直接编辑文本框中的内容
        # 辩词已经被显示，现在用户可以手动修改文本框的内容

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DebateApp()
    window.show()
    sys.exit(app.exec_())
